package gw.com.android.ui.quote2.addquote;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.android.utils.FontUtils;
import gw.com.android.utils.MobclickEventUtlis;
import gw.com.android.utils.PackStatis;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.app.ObjectSessionStore;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.CommonUtils;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.StringUtils;
import www.com.library.view.TintImageView;
import www.com.library.view.TintLinearLayout;

/**
 * 自选添加界面各板块产品列表适配器
 */
public class QuoteAddSelfAdapter extends RecyclerView.Adapter {

    private final String TAG = QuoteAddSelfAdapter.this.getClass().getSimpleName();

    /**
     * 产品布局加载器
     **/
    private LayoutInflater mInflater;
    /**
     * 上下文
     **/
    private BaseActivity mOwnerAct;
    /**
     * 记录当前是否正在刷新
     */
    private boolean onBind = false;
    private DataItemResult mList;// 所有产品的列表
    private DataItemResult mTmpList;
    private String mZoneType;
    private QuoteAddFragment mFragment;

    /**
     * 初始化界面数据
     *
     * @param context
     */
    public QuoteAddSelfAdapter(QuoteAddFragment fragment, String mZoneType, Context context) {
        super();
        mFragment = fragment;
        this.mZoneType = mZoneType;
        mOwnerAct = (BaseActivity) context;
        mInflater = LayoutInflater.from(context);
        mTmpList = DataManager.instance().getTickList(mZoneType);
        //在这里将mTempList进行过滤
        mList = new DataItemResult();
        mList.appendItems(mTmpList);
        DataManager.instance().getSortTickList(mList, AppContances.SORT_NORMAL_TYPE);
        Logger.e("QuoteSelfAddListAdapter   size = " + mList.getDataCount());
    }

    /**
     * 刷新界面排序后的数据
     */
    public void refreshSortData(int sortType) {
        mTmpList = DataManager.instance().getTickList(mZoneType);
        mList.clear();
        mList.appendItems(mTmpList);
        DataManager.instance().getSortTickList(mList, sortType);
        if (!onBind) {
            Logger.e("QuoteSelfAddListAdapter   size = " + mList.getDataCount());
            if (mFragment.isFragmentReady()) {
                notifyDataSetChanged();
            } else {
            }
        }
    }

    /**
     * 刷新当前更新的产品报价
     *
     * @param codeId
     */
    public void refreshData(int codeId) {
        if (!onBind) {
            for (int i = 0; i < mList.getDataCount(); i++) {
                DataItemDetail item = mList.getItem(i);
                if (null != item && item.getInt(GTSConst.JSON_KEY_CODEID) == codeId) {
//				    Logger.e("QuoteListAdapter refreshData 更新操作 codeId = " + codeId);
                    if (mFragment.isFragmentReady()) {
                        notifyItemChanged(i, item);
                    } else {
                    }
                    break;
                }
            }
        }
    }

    @Override
    public int getItemCount() {
        return null == mList ? 0 : mList.getDataCount();
    }

    private boolean ifTagViewUsed = false;

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final DataItemDetail item = getItem(position);
        QuoteItemView viewHolder = (QuoteItemView) holder;
        if (null != item) {
            viewHolder.itemView.setTag(item);

            //产品信息类型，是否为参考行情
            if (item.getInt(GTSConst.JSON_KEY_TRADESTATE) == AppContances.TRADE_STATU_REF || item.getInt(GTSConst.JSON_KEY_ZONE) == GTSConst.ZONE_TYPE_REF) {
                viewHolder.tvProductType.setText("参考");
                viewHolder.tvProductType.setSelected(true);
                viewHolder.tvProductType.setBackgroundDrawable(AppMain.getApp().getResources().getDrawable(R.drawable.common_edittext_bg_selector3));
                viewHolder.tvProductType.setTextColor(mOwnerAct.getResources().getColor(R.color.color_k));
                viewHolder.tvProductType.setVisibility(View.VISIBLE);
                ifTagViewUsed = true;
            } else {
                viewHolder.tvProductType.setVisibility(View.INVISIBLE);
                ifTagViewUsed = false;
            }

            //判断是否为 推荐产品,如果是，就加上推荐标签
            if (!ifTagViewUsed)
                if (DataManager.instance().ifRecommend(item)) {
                    viewHolder.tvProductType.setText("推荐");
                    viewHolder.tvProductType.setSelected(true);
                    viewHolder.tvProductType.setBackgroundDrawable(AppMain.getApp().getResources().getDrawable(R.drawable.common_edittext_bg_selector2));
                    viewHolder.tvProductType.setTextColor(mOwnerAct.getResources().getColor(R.color.color_chart_b));
                    viewHolder.tvProductType.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.tvProductType.setVisibility(View.INVISIBLE);
                }

            if (item.getString(GTSConst.JSON_KEY_BUYPRICE).equals("0.0") || item.getString(GTSConst.JSON_KEY_SELLPRICE).equals("0.0")) {
                setEmptyView(viewHolder);
                viewHolder.tvProductName.setText(DataManager.instance().getPrdName(item));
                viewHolder.tvProductSubName.setText(item.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME));
            } else {
                updateViews(viewHolder, item);
            }

            if (position == getItemCount() - 1) {//如果是最后一行
                viewHolder.vDivider_18.setVisibility(View.GONE);
                viewHolder.vDivider_0.setVisibility(View.VISIBLE);
            } else {
                viewHolder.vDivider_18.setVisibility(View.VISIBLE);
                viewHolder.vDivider_0.setVisibility(View.GONE);
            }
        } else {
            setEmptyView(viewHolder);
        }
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position, List payloads) {
        onBind = true;
//		Logger.e("QuoteListAdapter position == " + position + ", "+payloads.isEmpty());
        if (payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            final DataItemDetail item = (DataItemDetail) payloads.get(0);
            QuoteItemView viewholder = (QuoteItemView) holder;
            if (null != item) {
                viewholder.itemView.setTag(item);
                updateViews(viewholder, item);
            }
        }
        onBind = false;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup convertView, int viewType) {
        View v = mInflater.inflate(R.layout.list_item_quote_self_add, convertView, false);
        return new QuoteItemView(v);
    }

    public DataItemDetail getItem(int position) {
        if (position < 0 || position >= mList.getDataCount()) {
            return null;
        }

        if (null != mList && null != mList.getItem(position)) {
            return mList.getItem(position);
        }

        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * 更新展示界面数据，主要更新价格部分
     *
     * @param viewholder
     * @param mItem      产品对象
     */
    public void updateViews(QuoteItemView viewholder, final DataItemDetail mItem) {
//		AppUtil.error("prdName == " + prdName);
        viewholder.tvProductName.setText(DataManager.instance().getPrdName(mItem));
        viewholder.tvProductSubName.setText(AppMain.getAppString(R.string.quote_title_spread,
                mItem.getString(GTSConst.JSON_KEY_SUBSYMBOLNAME), mItem.getString(GTSConst.JSON_KEY_DIFF)));

        //产品信息类型，是否为参考行情
        if (mZoneType.equals(GTSConst.ZONE_TYPE_ALL + "")) {
            if (mItem.getInt(GTSConst.JSON_KEY_TRADESTATE) == AppContances.TRADE_STATU_REF || mItem.getInt(GTSConst.JSON_KEY_ZONE) == GTSConst.ZONE_TYPE_REF) {
                viewholder.tvProductType.setSelected(true);
                viewholder.tvProductType.setVisibility(View.VISIBLE);
            } else {
                viewholder.tvProductType.setVisibility(View.INVISIBLE);
            }
        }

        //涨幅
        int statu = AppContances.PRICE_UNCHANGE;
        if (mItem.getString(GTSConst.JSON_KEY_PERCENT).startsWith("-")) {
            statu = AppContances.PRICE_DECREASE;
        } else if (mItem.getString(GTSConst.JSON_KEY_PERCENT).startsWith("+")) {
            statu = AppContances.PRICE_INCREASE;
        }
        viewholder.tvPercentView.setText(mItem.getString(GTSConst.JSON_KEY_PERCENT) + "%");
        viewholder.tvPercentView.setTextColor(ColorThemeUtil.instance().getPriceColor(statu));

        viewholder.tvNewPrice.setText(mItem.getString(GTSConst.JSON_KEY_CURPRICE));

        //仓位数量
        int num = DataManager.instance().getPositionNum(mItem.getInt(GTSConst.JSON_KEY_CODEID));
        viewholder.tvProductState.setText(num + "");
        if (num <= 0) {//无仓位
            viewholder.tvProductState.setVisibility(View.INVISIBLE);
        } else {
            viewholder.tvProductState.setVisibility(View.VISIBLE);
        }

        if (mItem.getInt(GTSConst.JSON_KEY_ISSELECTED) == 1) {
            viewholder.tvProductAdd.setImageResource(R.mipmap.a_quote_choose);
            viewholder.tvProductAdd.setColorValue(ColorThemeUtil.instance().color_k, ColorThemeUtil.instance().color_k);
        } else {
            viewholder.tvProductAdd.setImageResource(R.mipmap.a_quote_editadd);
            viewholder.tvProductAdd.setColorValue(ColorThemeUtil.instance().color_c, ColorThemeUtil.instance().color_c);
        }

//		viewholder.productItemView.setColorValue(
//				ContextCompat.getColor(mOwnerAct, ColorThemeUtil.instance().getNewPriceBg(mItem.getInt(GTSConst.JSON_KEY_CURPRICEBGSTATE))),
//				ColorThemeUtil.instance().color_d);
    }

    /**
     * 设置空数据界面
     */
    private void setEmptyView(QuoteItemView viewHolder) {
        viewHolder.tvProductName.setText(StringUtils.NA_MSG);
        viewHolder.tvProductSubName.setText(StringUtils.NA_MSG);
        viewHolder.tvProductState.setVisibility(View.INVISIBLE);
        viewHolder.tvProductType.setVisibility(View.INVISIBLE);
        // 时间
        viewHolder.tvProductAdd.setVisibility(View.GONE);
        viewHolder.tvPercentView.setText(StringUtils.NA_MSG);
        viewHolder.tvPercentView.setTextColor(ColorThemeUtil.instance().color_c);

        // 现价
        viewHolder.tvNewPrice.setText(StringUtils.NA_MSG);
        viewHolder.tvNewPrice.setTextColor(ColorThemeUtil.instance().color_c);
        viewHolder.vDivider_18.setVisibility(View.GONE);
        viewHolder.vDivider_0.setVisibility(View.GONE);
    }

    public class QuoteItemView extends ViewHolder {
        @BindView(R.id.ll_product_item)
        public TintLinearLayout productItemView;
        @BindView(R.id.percent_view)
        public TextView tvPercentView;
        @BindView(R.id.add_view)
        public TintImageView tvProductAdd;
        @BindView(R.id.product_name)
        public TextView tvProductName;
        @BindView(R.id.product_sub_name)
        public TextView tvProductSubName;
        @BindView(R.id.product_states)
        public TextView tvProductState;
        @BindView(R.id.product_type)
        public TextView tvProductType;
        @BindView(R.id.new_price)
        public TextView tvNewPrice;
        @BindView(R.id.v_divider_18)
        public View vDivider_18;
        @BindView(R.id.v_divider_0)
        public View vDivider_0;

        public QuoteItemView(View convertView) {
            super(convertView);
            ButterKnife.bind(this, convertView);
            tvNewPrice.setTypeface(FontUtils.getDIN_MediumFont(mOwnerAct));
        }

        @OnClick(R.id.ll_product_item)
        void onProductClick() {
            if (CommonUtils.isFastDoubleClick()) {
                return;
            }
            DataItemDetail mTickModel = (DataItemDetail) itemView.getTag();
            if (null == mTickModel) {
                Logger.i("行情数据对象为空！！！");
                showErrorMsg(ConfigType.SERVER_ERROR_1021);
                return;
            }
            MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct, "ClickProduct3");
            if (mOwnerAct instanceof QuoteAddSelfActivity) {//把当前activity存入静态对象，以便在必要的时候将它finish
                ObjectSessionStore.setObject(QuoteAddSelfActivity.class.getSimpleName() + GTSDataListener.quoteAddNum, mOwnerAct);
            }
            PackStatis.getToService(PackStatis.EventAction.CLICKPRODUCT.getValue(), PackStatis.EventCategory.MARKET.getValue(), null, null);
            ActivityManager.showChartActivity(mOwnerAct, mTickModel.getInt(GTSConst.JSON_KEY_CODEID), mTickModel.getInt(GTSConst.JSON_KEY_ZONE), AppContances.TRADE_TYPE_FORM_QUOTE);
        }

        @OnClick(R.id.add_view)
        void onProductAddClick() {
            if (CommonUtils.isFastDoubleClick()) {
                return;
            }
            if (!NetworkMonitor.hasNetWork()) {
                return;
            }
            DataItemDetail mTickModel = (DataItemDetail) itemView.getTag();
            if (null != mTickModel) {
                if (mTickModel.getInt(GTSConst.JSON_KEY_ISSELECTED) == 0) {
                    mOwnerAct.showToastPopWindow(AppMain.getAppString(R.string.quote_menu_self_add_suc));
                    DataManager.instance().addSelfTick(mTickModel);
                    mTickModel.setIntValue(GTSConst.JSON_KEY_ISSELECTED, 1);
                    MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct, "ClickAdd2");
                } else {
                    mOwnerAct.showToastPopWindow(AppMain.getAppString(R.string.quote_menu_self_cancel_suc));
                    DataManager.instance().removeSelfTick(mTickModel);
                    mTickModel.setIntValue(GTSConst.JSON_KEY_ISSELECTED, 0);
                    MobclickEventUtlis.MobclickEventByAccountType(mOwnerAct, "ClickDelete3");
                }
                RxBus.getInstance().post(GTSConst.REPLY_QUOTE_SELF, mTickModel);
                AppTerminal.instance().saveCustomer(DataManager.instance().getSelfCodes());
                notifyDataSetChanged();
            }
        }

    }

    private void showErrorMsg(String errorId) {
        final PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(mOwnerAct, "", ConfigUtil.instance().getErrorConfigObject().optString(errorId));
        dialog.show();
    }

}
